package com.hs.room.repository

import android.content.Context
import com.hs.common.dto.SysRoleDto
import com.hs.common.repository.IRoleRepository
import com.hs.room.AppDatabase
import com.hs.room.mapper.RoleMapper
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject

/**
 * 角色的
 */
class RoleRoomRepository @Inject constructor(
    @ApplicationContext var context: Context,
    val database: AppDatabase
) : IRoleRepository {


    override suspend fun insertRole(role: SysRoleDto) {
        database.sysRoleDao().insertRole(RoleMapper.INSTANCE.roleDtoToRole(role))
    }

    override fun getAllRoles(): Flow<List<SysRoleDto>> {

        return flow {
            val roleFlow = database.sysRoleDao().getAllRoles()
                .filter { it.isNotEmpty() }
                .map { RoleMapper.INSTANCE.rolesToRoleDTOs(it) }
            emitAll(roleFlow)
        }.catch { e ->
            // 进行异常处理
            println("Error occurred while fetching getAllRoles data: $e")
        }
    }

    override suspend fun selectByCode(code: String): SysRoleDto {
        return RoleMapper.INSTANCE.roleToRoleDTO(database.sysRoleDao().selectByCode(code))
    }


}
